<template>
  <div class="weekly-plans">
    <div class="header">
      <h3>周工作计划</h3>
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog">创建周计划</el-button>
        <el-button type="success" @click="openAISuggestionDialog">
          <el-icon><MagicStick /></el-icon> AI 周度建议
        </el-button>
        <el-button type="danger" @click="batchDelete" :disabled="selectedPlans.length === 0">
          <el-icon><Delete /></el-icon> 批量删除 ({{ selectedPlans.length }})
        </el-button>
        <el-button @click="toggleSelectAll">
          {{ selectedPlans.length === plans.length && plans.length > 0 ? '取消全选' : '全选' }}
        </el-button>
      </div>
    </div>

    <!-- 计划列表 (卡片视图) -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="plans.length === 0" class="empty-state">
      <el-empty description="暂无周计划" />
    </div>

    <el-row v-else :gutter="20" class="plan-grid">
      <el-col 
        v-for="plan in plans" 
        :key="plan.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="8" 
        :xl="6"
      >
        <el-card 
          class="plan-card" 
          :class="{ 'is-selected': selectedPlans.includes(plan.id) }"
          shadow="hover"
          @click.stop="toggleSelection(plan.id)"
        >
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-checkbox 
                  :model-value="selectedPlans.includes(plan.id)"
                  @change="toggleSelection(plan.id)"
                  @click.stop
                />
                <span class="plan-date">{{ plan.year }}年{{ plan.month }}月 第{{ plan.week }}周</span>
              </div>
              <el-tag :type="getStatusType(plan.status)" size="small" effect="dark">
                {{ getStatusText(plan.status) }}
              </el-tag>
            </div>
          </template>
          
          <div class="card-content">
            <h4 class="plan-title" :title="plan.title">{{ plan.title }}</h4>
            
            <div class="plan-section">
              <div class="section-label">计划描述</div>
              <div class="section-text description" :class="{ 'empty': !plan.description }">
                {{ plan.description || '暂无描述内容' }}
              </div>
            </div>
            
            <div class="plan-section">
              <div class="section-label">目标摘要</div>
              <div class="section-text objectives">
                {{ plan.objectives || '暂无具体目标' }}
              </div>
            </div>
          </div>
          
          <div class="card-actions" @click.stop>
            <el-tooltip content="编辑计划" placement="top">
              <el-button circle size="small" type="warning" @click="editPlan(plan)">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>

            <el-tooltip content="提交周报" placement="top">
              <el-button circle size="small" type="primary" @click="submitWeeklyReport(plan)">
                <el-icon><Document /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="写日报" placement="top">
              <el-button circle size="small" type="info" @click="openDailyReportDialog(plan)">
                <el-icon><Calendar /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="删除计划" placement="top">
              <el-button circle size="small" type="danger" @click="deletePlan(plan)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 创建/编辑周计划对话框 -->
    <el-dialog v-model="showCreateDialog" :title="isEdit ? '编辑周计划' : '创建周计划'" width="600px">
      <el-alert
        v-if="isAIGenerated"
        title="这是AI生成的建议，您可以根据需要进行修改"
        type="info"
        show-icon
        closable
        style="margin-bottom: 20px;"
      />
      <el-form :model="newPlan" :rules="rules" ref="planFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-select v-model="newPlan.year" placeholder="选择年份" style="width: 100%">
                <el-option v-for="year in years" :key="year" :label="year" :value="year" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月份" prop="month">
              <el-select v-model="newPlan.month" placeholder="选择月份" style="width: 100%">
                <el-option v-for="month in months" :key="month.value" :label="month.label" :value="month.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="周数" prop="week">
          <el-select v-model="newPlan.week" placeholder="选择周数" style="width: 100%">
            <el-option v-for="week in weeks" :key="week" :label="`第${week}周`" :value="week" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="newPlan.title" placeholder="请输入计划标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="newPlan.description" type="textarea" :rows="3" placeholder="请输入计划描述" />
        </el-form-item>
        
        <el-form-item label="目标" prop="objectives">
          <el-input v-model="newPlan.objectives" type="textarea" :rows="4" placeholder="请输入具体目标和任务" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPlan" :loading="submitting">{{ isEdit ? '更新' : '创建' }}</el-button>
        <el-button v-if="isAIGenerated" type="success" @click="regenerateAISuggestion">
          <el-icon><MagicStick /></el-icon> 重新生成AI建议
        </el-button>
      </template>
    </el-dialog>

    <!-- AI 建议对话框 -->
    <el-dialog v-model="showAISuggestionDialog" title="AI 周度建议" width="600px">
      <el-form :model="aiSuggestionForm" label-width="100px">
        <el-form-item label="月度计划">
          <el-select 
            v-model="aiSuggestionForm.monthlyPlanId" 
            placeholder="选择月度计划（可选）"
            clearable
            @change="onMonthlyPlanChange"
            :loading="loadingMonthlyPlans"
            style="width: 100%"
          >
            <el-option 
              v-for="plan in monthlyPlans" 
              :key="plan.id" 
              :label="`${plan.year}年${plan.month}月 - ${plan.title}`" 
              :value="plan.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="自定义目标">
          <el-input 
            v-model="aiSuggestionForm.customGoal" 
            type="textarea" 
            :rows="4"
            placeholder="请描述您的工作目标和期望达成的成果..."
          />
        </el-form-item>
        
        <el-form-item label="关键指标">
          <el-input 
            v-model="aiSuggestionForm.keyMetrics" 
            type="textarea" 
            :rows="3"
            placeholder="请列出可量化的关键指标"
          />
        </el-form-item>
        
        <el-form-item label="选择周数">
          <el-select v-model="aiSuggestionForm.selectedWeek" placeholder="选择周数" style="width: 100%">
            <el-option v-for="week in weeks" :key="week" :label="`第${week}周`" :value="week" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAISuggestionDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateAISuggestion" 
          :loading="generatingAISuggestion"
        >
          生成AI建议
        </el-button>
      </template>
    </el-dialog>

    <!-- 写日报对话框 -->
    <el-dialog v-model="showDailyReportDialog" title="写日报" width="700px">
      <div class="daily-report-container">
        <div class="week-days">
          <div 
            v-for="day in weekDays" 
            :key="day.date"
            class="day-item"
            :class="{ 'active': currentDailyDate === day.date, 'has-content': day.hasContent }"
            @click="selectDailyDate(day.date)"
          >
            <div class="day-name">{{ day.name }}</div>
            <div class="day-date">{{ day.dateStr }}</div>
          </div>
        </div>
        
        <div class="daily-content-editor" v-if="currentDailyDate">
          <div class="editor-header">
            <span>{{ currentDailyDate }} 日报</span>
            <el-tag v-if="dailyReports[currentDailyDate]" type="success" size="small">已填写</el-tag>
          </div>
          <el-input
            v-model="currentDailyContent"
            type="textarea"
            :rows="10"
            placeholder="请输入今日工作内容、成果及遇到的问题..."
          />
          <div class="editor-footer">
            <el-button type="primary" @click="saveDailyReport" :loading="savingDailyReport">保存日报</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 提交周报对话框 -->
    <el-dialog v-model="showSubmitReportDialog" title="提交周报" width="700px">
      <el-form :model="reportForm" label-width="80px">
        <el-form-item label="工作成效">
          <el-input v-model="reportForm.achievements" type="textarea" :rows="4" placeholder="本周主要工作成果" />
        </el-form-item>
        <el-form-item label="存在问题">
          <el-input v-model="reportForm.challenges" type="textarea" :rows="3" placeholder="遇到的困难和挑战" />
        </el-form-item>
        <el-form-item label="下周计划">
          <el-input v-model="reportForm.next_week_plan" type="textarea" :rows="3" placeholder="下周工作安排" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSubmitReportDialog = false">取消</el-button>
        <el-button type="success" @click="generateReportContent" :loading="generatingReport">
          <el-icon><MagicStick /></el-icon> 基于日报生成
        </el-button>
        <el-button type="primary" @click="confirmSubmitReport" :loading="submittingReport">提交周报</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import { MagicStick, Delete, Document, Edit, Calendar } from '@element-plus/icons-vue'

export default {
  name: 'WeeklyPlans',
  components: {
    MagicStick,
    Delete,
    Document,
    Edit,
    Calendar
  },
  setup() {
    const authStore = useAuthStore()
    const plans = ref([])
    const monthlyPlans = ref([])
    const loading = ref(false)
    const loadingMonthlyPlans = ref(false)
    const submitting = ref(false)
    const showCreateDialog = ref(false)
    const showAISuggestionDialog = ref(false)
    const selectedPlans = ref([])
    const planFormRef = ref()
    const generatingAISuggestion = ref(false)
    const isAIGenerated = ref(false)
    const isEdit = ref(false)
    const editingId = ref(null)

    const newPlan = ref({
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      week: getCurrentWeek(),
      title: '',
      description: '',
      objectives: ''
    })

    const aiSuggestionForm = ref({
      monthlyPlanId: '',
      customGoal: '',
      keyMetrics: '',
      selectedWeek: getCurrentWeek()
    })

    // Daily Report State
    const showDailyReportDialog = ref(false)
    const currentPlan = ref(null)
    const weekDays = ref([])
    const currentDailyDate = ref('')
    const currentDailyContent = ref('')
    const dailyReports = ref({}) // Map date -> content
    const savingDailyReport = ref(false)

    // Submit Report State
    const showSubmitReportDialog = ref(false)
    const reportForm = ref({
      achievements: '',
      challenges: '',
      next_week_plan: ''
    })
    const generatingReport = ref(false)
    const submittingReport = ref(false)

    const years = ref([2023, 2024, 2025, 2026])
    const months = ref([
      { label: '一月', value: 1 }, { label: '二月', value: 2 }, { label: '三月', value: 3 },
      { label: '四月', value: 4 }, { label: '五月', value: 5 }, { label: '六月', value: 6 },
      { label: '七月', value: 7 }, { label: '八月', value: 8 }, { label: '九月', value: 9 },
      { label: '十月', value: 10 }, { label: '十一月', value: 11 }, { label: '十二月', value: 12 }
    ])
    const weeks = ref([1, 2, 3, 4, 5])

    const rules = {
      year: [{ required: true, message: '请选择年份', trigger: 'change' }],
      month: [{ required: true, message: '请选择月份', trigger: 'change' }],
      week: [{ required: true, message: '请选择周数', trigger: 'change' }],
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
    }

    function getCurrentWeek() {
      const now = new Date()
      const start = new Date(now.getFullYear(), 0, 1)
      const days = Math.floor((now - start) / (24 * 60 * 60 * 1000))
      return Math.ceil((days + start.getDay() + 1) / 7)
    }

    const getStatusType = (status) => {
      const types = {
        pending: 'info',
        in_progress: 'warning',
        completed: 'success'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        pending: '待开始',
        in_progress: '进行中',
        completed: '已完成'
      }
      return texts[status] || status
    }

    const openCreateDialog = () => {
      isEdit.value = false
      editingId.value = null
      resetForm()
      showCreateDialog.value = true
    }

    const openAISuggestionDialog = () => {
      showAISuggestionDialog.value = true
    }

    const editPlan = (plan) => {
      isEdit.value = true
      editingId.value = plan.id
      newPlan.value = {
        year: plan.year,
        month: plan.month,
        week: plan.week,
        title: plan.title,
        description: plan.description,
        objectives: plan.objectives
      }
      showCreateDialog.value = true
    }

    const generateAISuggestion = async () => {
      if (!aiSuggestionForm.value.monthlyPlanId && !aiSuggestionForm.value.customGoal.trim()) {
        ElMessage.error('请选择月度计划或输入自定义目标')
        return
      }

      generatingAISuggestion.value = true
      try {
        let content = ''
        let context = ''
        
        if (aiSuggestionForm.value.monthlyPlanId) {
          const selectedPlan = monthlyPlans.value.find(plan => plan.id === aiSuggestionForm.value.monthlyPlanId)
          if (selectedPlan) {
            content = `基于月度计划"${selectedPlan.title}" (目标: ${selectedPlan.objectives})`
            context = JSON.stringify(selectedPlan)
          }
        } else {
          content = `基于目标: ${aiSuggestionForm.value.customGoal}`
          if (aiSuggestionForm.value.keyMetrics) {
            content += `\n关键指标: ${aiSuggestionForm.value.keyMetrics}`
          }
        }

        const timeframe = `${new Date().getFullYear()}年${new Date().getMonth() + 1}月第${aiSuggestionForm.value.selectedWeek}周`

        const response = await axios.post('/api/ai-suggestions/plan-generation', {
          type: 'weekly',
          content: content,
          timeframe: timeframe,
          context: context
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        const aiData = response.data
        
        newPlan.value = {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          week: aiSuggestionForm.value.selectedWeek,
          title: aiData.title || `第${aiSuggestionForm.value.selectedWeek}周工作计划`,
          description: aiData.description || content,
          objectives: Array.isArray(aiData.tasks) ? aiData.tasks.join('\n') : (aiData.tasks || '')
        }

        // 标记为AI生成，显示编辑提示
        isAIGenerated.value = true
        showAISuggestionDialog.value = false
        showCreateDialog.value = true
        ElMessage.success('AI周计划建议已生成，请查看并根据需要修改')

      } catch (error) {
        console.error('AI建议生成错误:', error)
        ElMessage.error('AI建议生成失败，请稍后重试')
      } finally {
        generatingAISuggestion.value = false
      }
    }

    const batchDelete = async () => {
      if (selectedPlans.value.length === 0) {
        ElMessage.warning('请先选择要删除的计划')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedPlans.value.length} 个周计划吗？此操作不可恢复。`,
          '确认批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )

        const deletePromises = selectedPlans.value.map(id => 
          axios.delete(`/api/plans/weekly/${id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` }
          })
        )

        await Promise.all(deletePromises)
        ElMessage.success(`成功删除 ${selectedPlans.value.length} 个周计划`)
        selectedPlans.value = []
        fetchPlans()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const deletePlan = async (plan) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除周计划 "${plan.title}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await axios.delete(`/api/plans/weekly/${plan.id}`, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        ElMessage.success('删除成功')
        fetchPlans()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const toggleSelection = (id) => {
      const index = selectedPlans.value.indexOf(id)
      if (index === -1) {
        selectedPlans.value.push(id)
      } else {
        selectedPlans.value.splice(index, 1)
      }
    }

    const toggleSelectAll = () => {
      if (selectedPlans.value.length === plans.value.length && plans.value.length > 0) {
        selectedPlans.value = []
      } else {
        selectedPlans.value = plans.value.map(plan => plan.id)
      }
    }

    const submitPlan = async () => {
      if (!planFormRef.value) return
      
      await planFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            if (isEdit.value) {
              await axios.put(`/api/plans/weekly/${editingId.value}`, newPlan.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('周计划更新成功')
            } else {
              await axios.post('/api/plans/weekly', newPlan.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('周计划创建成功')
            }
            showCreateDialog.value = false
            resetForm()
            fetchPlans()
          } catch (error) {
            ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const resetForm = () => {
      newPlan.value = {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        week: getCurrentWeek(),
        title: '',
        description: '',
        objectives: ''
      }
      isAIGenerated.value = false
    }

    const regenerateAISuggestion = () => {
      // 重新打开AI建议对话框，保留之前的设置
      showCreateDialog.value = false
      showAISuggestionDialog.value = true
    }

    const fetchPlans = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/plans/weekly', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        plans.value = response.data
      } catch (error) {
        ElMessage.error('获取周计划失败')
      } finally {
        loading.value = false
      }
    }

    const fetchMonthlyPlans = async () => {
      loadingMonthlyPlans.value = true
      try {
        const response = await axios.get('/api/plans/monthly', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        monthlyPlans.value = response.data
      } catch (error) {
        ElMessage.error('获取月度计划失败')
      } finally {
        loadingMonthlyPlans.value = false
      }
    }

    const onMonthlyPlanChange = (monthlyPlanId) => {
      if (monthlyPlanId) {
        const selectedPlan = monthlyPlans.value.find(plan => plan.id === monthlyPlanId)
        if (selectedPlan) {
          // 自动填充基于月度计划的信息
          aiSuggestionForm.value.customGoal = `基于月度计划"${selectedPlan.title}"的周度分解`
          aiSuggestionForm.value.keyMetrics = selectedPlan.objectives || ''
        }
      } else {
        // 清空自定义目标
        aiSuggestionForm.value.customGoal = ''
        aiSuggestionForm.value.keyMetrics = ''
      }
    }

    // Daily Report Logic
    const openDailyReportDialog = async (plan) => {
      currentPlan.value = plan
      calculateWeekDays(plan.year, plan.week)
      await fetchDailyReports(plan.id)
      
      // Select today if in range, otherwise first day
      const today = new Date().toISOString().split('T')[0]
      const todayInWeek = weekDays.value.find(d => d.date === today)
      
      if (todayInWeek) {
        selectDailyDate(today)
      } else {
        selectDailyDate(weekDays.value[0].date)
      }
      
      showDailyReportDialog.value = true
    }

    const calculateWeekDays = (year, week) => {
      const simple = new Date(year, 0, 1 + (week - 1) * 7);
      const dow = simple.getDay();
      const ISOweekStart = simple;
      if (dow <= 4)
          ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
      else
          ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
      
      const days = []
      const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      
      for (let i = 0; i < 7; i++) {
        const d = new Date(ISOweekStart)
        d.setDate(ISOweekStart.getDate() + i)
        const dateStr = d.toISOString().split('T')[0]
        days.push({
          name: dayNames[i],
          date: dateStr,
          dateStr: `${d.getMonth() + 1}/${d.getDate()}`,
          hasContent: false // Will be updated after fetch
        })
      }
      weekDays.value = days
    }

    const fetchDailyReports = async (planId) => {
      try {
        const response = await axios.get('/api/reports/daily', {
          params: { weekly_plan_id: planId },
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        const reports = {}
        response.data.forEach(r => {
          reports[r.date] = r.content
        })
        dailyReports.value = reports
        
        // Update hasContent
        weekDays.value.forEach(d => {
          d.hasContent = !!reports[d.date]
        })
      } catch (error) {
        console.error('获取日报失败:', error)
        ElMessage.error('获取日报失败')
      }
    }

    const selectDailyDate = (date) => {
      currentDailyDate.value = date
      currentDailyContent.value = dailyReports.value[date] || ''
    }

    const saveDailyReport = async () => {
      if (!currentDailyContent.value.trim()) {
        ElMessage.warning('请输入日报内容')
        return
      }
      
      savingDailyReport.value = true
      try {
        await axios.post('/api/reports/daily', {
          weekly_plan_id: currentPlan.value.id,
          date: currentDailyDate.value,
          content: currentDailyContent.value
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        dailyReports.value[currentDailyDate.value] = currentDailyContent.value
        
        // Update UI indicator
        const day = weekDays.value.find(d => d.date === currentDailyDate.value)
        if (day) day.hasContent = true
        
        ElMessage.success('日报保存成功')
      } catch (error) {
        console.error('保存日报失败:', error)
        ElMessage.error('保存日报失败')
      } finally {
        savingDailyReport.value = false
      }
    }

    // Submit Weekly Report Logic
    const submitWeeklyReport = (plan) => {
      currentPlan.value = plan
      reportForm.value = {
        achievements: '',
        challenges: '',
        next_week_plan: ''
      }
      showSubmitReportDialog.value = true
      // Auto generate content initially? Maybe let user click button.
      // Or auto generate if empty.
      generateReportContent()
    }

    const generateReportContent = async () => {
      generatingReport.value = true
      try {
        const response = await axios.post('/api/reports/weekly/generate-content', {
          planId: currentPlan.value.id,
          week: currentPlan.value.week,
          month: currentPlan.value.month,
          year: currentPlan.value.year
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        const data = response.data
        reportForm.value = {
          achievements: data.achievements || '',
          challenges: data.challenges || '',
          next_week_plan: data.next_week_plan || ''
        }
        
        ElMessage.success('已根据日报和计划生成周报草稿')
      } catch (error) {
        console.error('生成周报内容失败:', error)
        ElMessage.error('生成内容失败')
      } finally {
        generatingReport.value = false
      }
    }

    const confirmSubmitReport = async () => {
      submittingReport.value = true
      try {
        const response = await axios.post('/api/reports/weekly', {
          weekly_plan_id: currentPlan.value.id,
          week: currentPlan.value.week,
          month: currentPlan.value.month,
          year: currentPlan.value.year,
          achievements: reportForm.value.achievements,
          challenges: reportForm.value.challenges,
          next_week_plan: reportForm.value.next_week_plan
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        ElMessage.success('周报提交成功')
        
        // Update plan status locally or refresh
        const plan = plans.value.find(p => p.id === currentPlan.value.id)
        if (plan) plan.status = 'completed'
        
        showSubmitReportDialog.value = false
      } catch (error) {
        console.error('提交周报失败:', error)
        ElMessage.error('提交周报失败')
      } finally {
        submittingReport.value = false
      }
    }

    onMounted(() => {
      fetchPlans()
      fetchMonthlyPlans()
    })
    
    return {
      plans,
      monthlyPlans,
      loading,
      loadingMonthlyPlans,
      submitting,
      showCreateDialog,
      showAISuggestionDialog,
      selectedPlans,
      newPlan,
      aiSuggestionForm,
      planFormRef,
      years,
      months,
      weeks,
      rules,
      generatingAISuggestion,
      isAIGenerated,
      isEdit,
      editingId,
      openCreateDialog,
      openAISuggestionDialog,
      editPlan,
      editPlan,
      batchDelete,
      deletePlan,
      toggleSelection,
      toggleSelectAll,
      submitPlan,
      generateAISuggestion,
      regenerateAISuggestion,
      onMonthlyPlanChange,
      openDailyReportDialog,
      saveDailyReport,
      selectDailyDate,
      showDailyReportDialog,
      weekDays,
      currentDailyDate,
      currentDailyContent,
      dailyReports,
      savingDailyReport,
      showSubmitReportDialog,
      reportForm,
      generatingReport,
      submittingReport,
      generateReportContent,
      confirmSubmitReport,
      submitWeeklyReport,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.weekly-plans {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
}

/* Card Grid Styles */
.plan-grid {
  margin-top: 20px;
}

.plan-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  position: relative;
}

.plan-card.is-selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.plan-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.plan-date {
  font-weight: 600;
  font-size: 1.05em;
  color: #2c3e50;
}

.card-content {
  padding: 10px 0;
}

.plan-title {
  margin: 0 0 15px 0;
  font-size: 1.2em;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.plan-section {
  margin-bottom: 12px;
}

.section-label {
  font-size: 0.85em;
  color: #909399;
  margin-bottom: 4px;
}

.section-text {
  font-size: 0.95em;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.section-text.description {
  min-height: 2.8em;
}

.section-text.empty {
  color: #c0c4cc;
  font-style: italic;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e4e7ed;
}

/* Daily Report Styles */
.daily-report-container {
  display: flex;
  height: 500px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.week-days {
  width: 150px;
  border-right: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.day-item {
  padding: 15px 10px;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

.day-item:hover {
  background-color: #e6f1fc;
}

.day-item.active {
  background-color: #ecf5ff;
  border-right: 3px solid #409eff;
}

.day-item.has-content .day-name::after {
  content: '●';
  color: #67c23a;
  font-size: 12px;
  margin-left: 5px;
}

.day-name {
  font-weight: bold;
  color: #303133;
}

.day-date {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.daily-content-editor {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.editor-footer {
  margin-top: 15px;
  text-align: right;
}
</style>
